package com.epam.qanda.web.servlet.admin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.qanda.db.model.ModeratorCategory;
import com.epam.qanda.db.service.ModeratorCategoryService;
import com.epam.qanda.db.service.UserService;

public class AppointingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger("stdout");

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String appoint = request.getParameter("appoint");
		String url = request.getServletPath();

		if (url.equals("/appointing")) {
			int userId = Integer.parseInt(appoint);
			new UserService().changeRole(userId, 3);
			new ModeratorCategoryService().deleteByUserId(userId);
			LOG.info("Moderator with id " + userId + " became a simple user");

		}

		if (url.equals("/selCategory")) {
			int id = Integer.parseInt(request.getParameter("uID"));
			new UserService().changeRole(id, 2);
			String[] checkCategories = request
					.getParameterValues("addCategory");
			if (checkCategories != null && checkCategories.length > 0) {
				for (String s : checkCategories) {
					ModeratorCategory element = new ModeratorCategory();
					element.setUserId(id);
					element.setCategoryId(Integer.parseInt(s));
					new ModeratorCategoryService().create(element);
				}
				LOG.info("User with id " + id + " became a moderator");
			}

		}

		response.sendRedirect(request.getHeader("Referer"));
	}
}